package com.example.linearlist;

import java.util.Iterator;

// 线性表的顺序存储结构（又称顺序表）
public class SequenceList<T> {

    private Object[] elements;
    private int length;

    public SequenceList(int capacity){
        elements = new Object[capacity];
    }

    public int getLength(){
        return length;
    }

    // 按序号查找(index从0开始)
    public T get(int index){
        if(index < 0 || index >= length){
            throw new IndexOutOfBoundsException(String.format("index: %d , size: %d", index, length));
        }
        return (T)elements[index];
    }

    // 按内容查找序号
    // 找不到则返回-1
    public int indexOf(T element){
        for (int i = 0; i < length; i++) {
            if(element == null && elements[i] == null){
                return i;
            }
            if(element != null && element.equals(elements[i])){
                return i;
            }
        }
        return -1;
    }

    public void set(int index, T element){
        if(index < 0 || index >= length){
            throw new IndexOutOfBoundsException("index: " + index + ", size: " + length);
        }
        elements[index] = element;
    }

    public void add(T element){
        if(length >= elements.length){
            throw new IndexOutOfBoundsException("空间已满");
        }
        elements[length] = element;
        length++;
    }

    public Iterator<T> iterator(){
        return new Iterator<T>() {
            private int index = -1;

            @Override
            public boolean hasNext() {
                return index < SequenceList.this.length-1;
            }

            @Override
            public T next() {
                index++;
                return (T)elements[index];
            }
        };
    }
}
